<template>
	<div class="bg-gray-100 h-screen">
		<div id="container" :style="{ height: showChoose ? '55vh' : '75vh' }"></div>
	</div>
</template>
<script setup>
import AMapLoader from "@amap/amap-jsapi-loader";

import { onMounted, onUnmounted, ref } from "vue";
import { useRouter } from "vue-router";
import { getCarPositionList } from "@/api/drive";
// window._AMapSecurityConfig = {
// 	securityJsCode: "34f6a037c26acc06c1df5d7f15efd0a1",
// };

// 地图实例
let map = null;

// 车辆位置
const carMap = ref({});

const showChoose = ref(true);

const router = useRouter();

onMounted(() => {
	AMapLoader.load({
		key: "b8443bf0d6c803f350308eaf819eaebf", // 申请好的Web端开发者Key，首次调用 load 时必填
		version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
		plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
	})
		.then((AMap) => {
			map = new AMap.Map("container", {
				// 设置地图容器id
				viewMode: "2D", // 是否为3D地图模式
				zoom: 17, // 初始化地图级别
				center: [104.598563, 31.453966], // 初始化地图中心点位置
			});
			//refreshCarPosition();
			// // 创建一个 Marker 实例：
			// const marker = new AMap.Marker({
			// 	isCustom: true, // 使用自定义点标记
			// 	position: [104.598563,31.453966], // 设置标注点坐标
			// 	content: '<img src="/car.png" class="car1" style="width: 6vw;height: 6vh" />',
			// 	map: map, // 设置标注点所在地图实例
			// });
		})
		.catch((e) => {
			console.log(e);
		});
});
/**
 * 2s 刷新一次车辆位置
 */
let refreshCarPositionTimer = null;
const refreshCarPosition = () => {
	refreshCarPositionTimer = setInterval(async () => {
		const carPositionListResult = await getCarPositionList();
		if (carPositionListResult) {
			for (let i = 0; i < carPositionListResult.data.length; i++) {
				let data = carPositionListResult.data[i];
				if (carMap.value[data.carId]) {
					carMap.value[data.carId].setPosition(data.position.split(","));
				} else {
					carMap.value[data.carId] = new AMap.Marker({
						isCustom: true, // 使用自定义点标记
						position: data.position.split(","), // 设置标注点坐标
						content: '<img src="/car.png" style="width: 6vw;height: 6vh" />',
						map: map, // 设置标注点所在地图实例
					});
				}
			}
		}
	}, 3000);
};

onUnmounted(() => {
	map?.destroy();
	if (refreshCarPositionTimer) {
		clearInterval(refreshCarPositionTimer);
		refreshCarPositionTimer = null;
	}
});
</script>
<style scoped>
#container {
	width: 100vw;
	height: 75vh;
}
</style>
